<?php
namespace app\admin\controller;
use think\Db;
class Ordergoods extends Base
{
    //列表
    public function lists(){
        if(is_post()){
            $d = $this->post;
            $map = [];
            if($d['keyword']!='') $map[] = ['and','c.title|w.name|u.name','like',"%{$d['keyword']}%"];
            if($d['status']!='') $map[] = ['and','o.status','=',$d['status']];
            if($d['min_time']!='') $map[] = ['and','o.create_time','>=',strtotime($d['min_time'])];
            if($d['max_time']!='') $map[] = ['and','o.create_time','<=',strtotime($d['max_time'])];
            $w  = where($map);
            $sql = "
                SELECT
                    o.*, c.title as ctitle, w.name as wname, u.name as uname,s.name as sname
                FROM
                  order_goods o
                left join
                  user u
                on
                  o.user_id=u.id
                left join
                  company c
                on
                  o.company_id=c.id
                left join
                  worker w
                on
                  o.worker_id=w.id
                left join
                  user s
                on
                  o.share_user_id=u.id
                    $w[0]
                ORDER BY
                    o.id
                DESC
            ";
            $rs = $this->db->query($sql.limit($d['page'],$d['limit']), $w[1],'',true);
            if($rs){
                foreach($rs[0] as $k => $v){
                  $rs[0][$k]['status'] = c("type.order_goods_status.{$v['status']}");
                  $rs[0][$k]['create_time'] = com_time_format($v['create_time']);
                }
                suc($rs[0],$rs[1]);
            }else{
                suc([],0);
            }
        }
        $this->fetch(['status'=>c('type.order_goods_status')]);
    }

    //添加订单
    function add(){
      if(is_post()){
        $d = $this->post;
        $rule = [
            'user_id' => "require",
            'goods_id'=> "require",
            'company_id'=> "require",
            'worker_id'=> "require",
            'fw_times'=> "require|integer",
            'start_time'=> "require",
            'end_time'=> "require",
            'price'=> "require|number|egt:0",
            'cost_price'=> "require|number|egt:0",
        ];
        $msg = [
          'user_id.require'=>'请选择下单人',
          'goods_id.require'=>'请选择服务项目',
          'worker_id.require'=>'请选择服务人',
          'price.require'=>'请输入服务价格',
          'cost_price.require'=>'请输入成本价格',
          'start_time.require'=>'请选择开始时间',
          'end_time.require'=>'请选择结束时间',
        ];
        check($rule,$msg,$d);
        if($d['price']<$d['cost_price']){
          err('服务价格不能低于成本价格');
        }
        $d['start_time'] = strtotime($d['start_time']);
        $d['end_time'] = strtotime($d['end_time']);
        $d['pv'] = $d['price']-$d['cost_price'];
        $user = $this->db->find('user',$d['user_id']);
        $d['user_pv'] = $d['pv']*c('type.order_goods_user_pv')[$user['level']];
        $d['s_user_id'] = $user['s_id'];
        $d['create_time'] = time();
        $d['order_no'] = $this->com_order_no();
        $id = $this->db->insert('order_goods',$d);
        if ($id) {
            cookie('js_msg','添加成功');
            cookie('js_function','preload');
            return suc();
        }else{
            err('添加失败');
        }
      }
      $this->fetch();
    }

    //编辑
    function edit(){
      if(is_post()){
        $d = $this->post;
        $rule = [
            'fw_times'=> "require|integer",
            'start_time'=> "require",
            'end_time'=> "require",
            'price'=> "require|number|egt:0",
            'cost_price'=> "require|number|egt:0",
        ];
        $msg = [
          'price.require'=>'请输入服务价格',
          'cost_price.require'=>'请输入成本价格',
          'start_time.require'=>'请选择开始时间',
          'end_time.require'=>'请选择结束时间',
        ];
        check($rule,$msg,$d);
        $info = $this->db->find('order_goods',$d['id']);
        if($info['status']!=0){
          err('订单状态已锁定,不能修改');
        }
        $d['start_time'] = strtotime($d['start_time']);
        $d['end_time'] = strtotime($d['end_time']);
        $d['update_time'] = time();
        $d['pv'] = $d['price']-$d['cost_price'];
        $user = $this->db->find('user',$info['user_id']);
        $d['user_pv'] = $d['pv']*c('type.order_goods_user_pv')[$user['level']];
        $rs = $this->db->update('order_goods',$d);
        if ($rs) {
            cookie('js_msg','编辑成功');
            cookie('js_function','preload');
            return suc();
        }else{
            err('编辑失败');
        }
      }
      $id = $this->get('id');
      $sql = "
          SELECT
              o.*,
              u.name as uname,u.phone as uphone, u.level as ulevel,
              g.title as gtitle,g.money as gmoney,
              c.title as ctitle,
              w.name as wname
          FROM
            order_goods o
          left join
            user u
          on
            o.user_id=u.id
          left join
            company c
          on
            o.company_id=c.id
          left join
            worker w
          on
            o.worker_id=w.id
          left join
            goods g
          on
            o.goods_id=g.id
          where o.id=?
      ";
      $info = $this->db->query($sql, [$id],1);
      $this->fetch(['info'=>$info]);
    }

    //选择分享会员
    function suser(){
        if(is_post()){
            $d = $this->post;
            $map = [];
            if($d['keyword']!='') $map[] = ['and','a.name|a.phone','like',"%{$d['keyword']}%"];
            if($d['level']!='') $map[] = ['and','a.level','=',$d['level']];
            $w  = where($map);
            $rs = $this->db->query("select a.*,b.name s_name from user a left join user b on a.s_id = b.id $w[0] order by id desc".limit($d['page'],$d['limit']), $w[1],'',true);
            if($rs){
                $rule = [
                    'status' => function($v){return c("type.status.{$v}");},
                    'level' => function($v){return c("type.user_level.{$v}");},
                    'create_time' => 'com_time_format',
                ];
                $data = com_format($rs[0],$rule);
                suc($data,$rs[1]);
            }else{
                suc([],0);
            }
        }
        $this->fetch();
    }

    //选择下单人
    function cuser(){
        if(is_post()){
            $d = $this->post;
            $map = [];
            if($d['keyword']!='') $map[] = ['and','a.name|a.phone','like',"%{$d['keyword']}%"];
            if($d['level']!='') $map[] = ['and','a.level','=',$d['level']];
            $map[] = ['and','a.status','=',0];
            $w  = where($map);
            $rs = $this->db->query("select a.*,b.name s_name from user a left join user b on a.s_id = b.id $w[0] order by id desc".limit($d['page'],$d['limit']), $w[1],'',true);
            if($rs){
                $rule = [
                    'status' => function($v){return c("type.status.{$v}");},
                    'level' => function($v){return c("type.user_level.{$v}");},
                    'create_time' => 'com_time_format',
                ];
                $data = com_format($rs[0],$rule);
                suc($data,$rs[1]);
            }else{
                suc([],0);
            }
        }
        $this->fetch();
    }

    //选择服务项目
    function cgoods(){
        if(is_post()){
            $d = $this->post;
            $map = [];
            if($d['keyword']!=''){ $map[] = ['and','a.title','like',"%{$d['keyword']}%"]; }
            $map[] = ['and','a.status','=',0];
            // if($d['max_time']!='') $map[] = ['and','a.create_time','<=',strtotime($d['max_time'])];
            if($d['cat_id']!=''){
                $ids = m('GoodsCat','c')->getAllchildCat($d['cat_id']);
                if($ids){
                    $ids[] = $d['cat_id'];
                }else{
                    $ids = [$d['cat_id']];
                }
                $map[] = ['and','a.cat_id','in',$ids];
            }
            $w  = where($map);
            $rs = $this->db->query("SELECT a.*,b.cat_title ptitle FROM goods a LEFT JOIN goods_cat b ON a.cat_id = b.id  $w[0] ORDER BY a.sort DESC,a.id DESC".limit($d['page'],$d['limit']), $w[1],'',true);
            if($rs){
                $rule = [
                    'status'=>function($v){return c("type.status.$v");},
                    'create_time' => 'com_time_format',
                ];
                $data = com_format($rs[0],$rule);
                suc($data,$rs[1]);
            }else{
                suc([],0);
            }
            $this->fetch();
        }
        $cat = m('GoodsCat','c')->allSubCat();
        return $this->fetch(['cat'=>$cat]);
    }

    //选择服务人
    function cworker(){
      if(is_post()){
          $d = $this->post;
          $map = [];
          if($d['keyword']!=''){ $map[] = ['and','name|phone','like',"%{$d['keyword']}%"]; }
          if($d['company_id']!=''){ $map[] = ['and','company_ids','like',"%,{$d['company_id']},%"]; }
          $map[] = ['and','status','=',0];
          $w  = where($map);
          $sql = "
              SELECT
                  id,
                  name,
                  phone,
                  age,
                  sex,
                  address,
                  area,
                  status,
                  sort,
                  create_time
              FROM
                  worker
              $w[0]
              ORDER BY
                  sort
              DESC,
                  id
              DESC
          ";
          $rs = $this->db->query($sql.limit($d['page'],$d['limit']), $w[1],'',true);
          if($rs){
              $rule = [
                  'status'=>function($v){return c("type.status.$v");},
                  'sex'=>function($v){return c("type.sex.$v");},
                  'create_time' => 'com_time_format',
              ];
              $data = com_format($rs[0],$rule);
              suc($data,$rs[1]);
          }else{
              suc([],0);
          }
      }
      $company_id = $this->get('company_id');
      if($company_id){
        $company = $this->db->find('company',$company_id);
        $this->fetch(['company'=>$company],'ordergoods/cworker');
      }else{
        $this->fetch([],'ordergoods/ccompany');
      }
    }

    //更新状态
    public function upStatus(){
        if(is_post()){
          $d = $this->post;
          $rule = [
            'id' => "require",
            'status' => "require",
            'fw_note' => "require",
          ];
          $msg = [
          ];
          check($rule,$msg,$d);
          $info = $this->db->find('order_goods',$d['id']);
          if($info['status']!=0){
            err('订单状态已锁定,不能修改');
          }

          //有推荐人
          if($info['s_user_id']){
              $s_user = $this->db->find('user',$info['s_user_id']);
              $this->db->begin();
              $mysql = [];
              //order_goods
              $data = [
                'id' => $d['id'],
                'status'=>$d['status'],
                'fw_note'=>$d['fw_note'],
                'update_time'=>time(),
              ];
              $mysql[] = $this->db->update('order_goods',$data);
              #完成订单, 推荐人得反佣
              if($d['status']==1 && $s_user["level"] > 0){
                //award_fanyong
                $data = [
                  "order_no"=>$this->com_order_no(),
                  "order_goods_id"=>$d['id'],
                  "user_id"=>$s_user['id'],
                  "user_level"=>$s_user['level'],
                  "pv"=>$info['pv'],
                  "fee"=>c("type.award_fanyong_fee")[$s_user['level']],
                  "create_time"=>time(),
                ];
                $data['money'] = bcmul($data['fee'],$data['pv'],2);
                $mysql[] = $id = $this->db->insert('award_fanyong',$data);
                //发奖
                $mysql[] = m('userbill','xcom')->doit($data['order_no'], $data['user_id'], 107,'award_fanyong', $id,$data['money'],'money');
              }
              $rs = $this->db->end($mysql);
              if ($rs) {
                  cookie('js_msg','更新状态成功');
                  cookie('js_function','preload');
                  return suc();
              }else{
                  err('更新状态失败');
              }
              m('log','xcom')->record($this->userinfo['id'], "更新订单状态:".json_encode($d,JSON_UNESCAPED_UNICODE),"admin_user");
          //无推荐人
          }else{
              $d['update_time'] = time();
              $this->db->update('order_goods', $d);
              m('log','xcom')->record($this->userinfo['id'], "更新订单状态:".json_encode($d,JSON_UNESCAPED_UNICODE),"admin_user");
              cookie('js_msg','更新状态成功');
              cookie('js_function','preload');
              suc();
          }
        }
    }

    //公司详情
    public function detail(){

        if(is_post()){
          $d = $this->post;
          $rule = [
            'id' => "require",
            'status' => "require",
          ];
          $msg = [
          ];
          check($rule,$msg,$d);

          $rs = $this->db->update('order_goods',$d);
          if ($rs) {
              cookie('js_msg','修改成功');
              cookie('js_function','preload');
              return suc();
          }else{
              err('修改失败');
          }
        }

        $id = $this->get("id");
        $sql = "
                SELECT
                    o.id,
                    o.order_no,
                    o.cost_price,
                    o.price,
                    o.pv,
                    o.money AS o_money,
                    o.start_time,
                    o.end_time,
                    o.fw_times,
                    o.fw_address,
                    o.fw_name,
                    o.fw_phone,
                    o.note AS o_note,
                    o.fw_note,
                    o.status AS o_status,
                    o.create_time AS o_create_time,
                    u.name AS u_name,
                    u.phone AS u_phone,
                    u.level AS u_level,
                    u.address AS u_address,
                    u.money AS u_money,
                    u.status AS u_status,
                    u.create_time AS u_create_time,
                    c.title,
                    c.phone AS c_phone,
                    c.username,
                    c.address AS c_address,
                    c.status AS c_status,
                    c.note AS c_note,
                    c.create_time AS c_create_time,
                    w.name AS w_name,
                    w.phone AS w_phone,
                    w.age,
                    w.sex,
                    w.address AS w_address,
                    w.area,
                    w.status AS w_status,
                    w.note AS w_note,
                    w.score,
                    w.create_time AS w_create_time,
                    g.title AS g_title,
                    g.money AS g_money,
                    g.content AS g_content,
                    g.status AS g_status,
                    g.create_time AS g_create_time
                FROM
                  order_goods o
                LEFT JOIN user u ON o.user_id=u.id
                LEFT JOIN company c ON o.company_id=c.id
                LEFT JOIN worker w ON o.worker_id=w.id
                LEFT JOIN goods g ON o.goods_id=g.id
                WHERE
                  o.id = ?
                ORDER BY
                    o.id
                DESC
            ";
        $info = $this->db->query($sql,[$id],1);
        $this->fetch(['info'=>$info]);
    }
}
